<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>交易中心</title>
		<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
		<script language="javascript" type="text/javascript" src="../js/js/baseJs.js"></script>
	</head>
	<body>
		<div class="trading-center-wrapper" id="tradingCenter" style="display: none;">
			<div class="wap-header" style="background: #323848;">交易中心
				<a class="back" onClick="javascript:window.history.back();return false;"></a>
			</div>
			<div class="tab-c">
				<div style="display: flex;flex-direction: row;">
					<div class="tab" :class="{on:currentType=='2'}" @click="showSaleData()">出售</div>
					<div class="tab" :class="{on:currentType=='1'}" @click="showBuyData()">求购</div>					
				</div>
				<div style="display: flex;flex-direction: row;">
					<div class="sale-btn"  style="margin-right: .1rem;" @click="showBuyJzzDemand">我要求购</div>
					<div class="sale-btn" @click="saleJzz">我要出售</div>
				</div>
			</div>
			<div class="item-wrapper" id="itemScrollContent">
				<div style="width: 100%">
					<div class="item-c" v-for="item in jzzListData">
						<div class="title-c">
							<div style="display: flex;flex-direction: row;">
								<div class="name" v-if="item.userName">{{item.userName}}</div>
								<div class="name" v-else>***</div>
								<div class="ico"></div>
								<div class="name" style="margin-left: .1rem;">{{item.status|status}}</div>
							</div>
							<div class="time">{{item.createTime|formatData}}</div>
						</div>
						<div class="number">出售数量：{{item.jzzNumber}}枚</div>
						<div class="line-c">
							<div>价格：</div>
							<div class="price">￥{{getSellTotalPrice(goldSeedAccountData.currentPrice,item.jzzNumber)}}</div>
						</div>
						<div class="line-c">
							<div class="ico-c">
								<div class="yinglian"></div>
							</div>
							<div class="buy-btn" v-if="currentType=='2'&&item.status=='0'" @click="showBuyInfo(item)">购买</div>
							<div class="buy-btn" v-if="currentType=='1'" @click="toSellJzz(item)">出售</div>
						</div>
					</div>
				</div>
			</div>
			<div class="black-background" v-if="showSaleJzz||showBuyJzzInfo||showBuyJzz" @click="showSaleJzz=false,showBuyJzz=false,showBuyJzzInfo=false,payImgUrlList=[]"></div>
			<div class="sale-jzz" v-if="showSaleJzz">
				<div class="sale-number">
					<div class="title-c">出售数量</div>
					<div class="right-c">
						<input v-model="saleNumber">
					</div>
				</div>
				<div class="type-selected">
					<!-- <div class="select"><span></span>支付宝</div> -->
					<div class="select" style="margin: 0 0 .4rem .4rem;"><span></span>支持支付方式： 银联</div>
				</div>
				<div class="confirm-bt" @click="confirmSaleJzz">确定</div>
			</div>
			<div class="sale-jzz" v-if="showBuyJzz">
				<div class="sale-number">
					<div class="title-c">求购数量</div>
					<div class="right-c">
						<input v-model="buyNumber">
					</div>
				</div>
				<div class="confirm-bt" @click="confirmCreatedBuyJzz">确定</div>
			</div>
			<div class="sale-jzz" v-if="showBuyJzzInfo">
				<div class="sale-number">
					<div class="title-c">银行名称</div>
					<div class="right-c">{{currentBuyJzzInfo.accountType}}</div>
				</div>
				<div class="sale-number">
					<div class="title-c">银行卡号</div>
					<div class="right-c">{{currentBuyJzzInfo.account}}</div>
				</div>
				<div class="sale-number">
					<div class="title-c">姓名</div>
					<div class="right-c">{{currentBuyJzzInfo.accountName}}</div>
				</div>
				<!-- <div class="sale-number">
					<div class="title-c">付款凭证</div>
					<div style="display:flex;flex-direction:row">
						<div class="upload-wrap">
							<div class="box" v-if="payImgTempList.length==0">
								<label class="p dotted">
									<input type="file" accept="image/*" name="file" @change="onChooseImage($event,3)">
									<img src="../image/add_ico.png" alt="">
								</label>
							</div>
							<template v-for="(imgIndex,imgItem) in payImgTempList">
								<div class="box">
									<div class="image-c">
										<img :src="imgItem">
										<div class="delete" @click.stop="deleteImg(imgIndex,payImgTempList)">
											<img src="../image/close_ico.png" alt="">
										</div>
									</div>
								</div>
							</template>
						</div>
					</div>
				</div> -->
				<div class="confirm-bt" @click="confirmBuyJzz">确定</div>
			</div>
			<!--  压缩图片用的  -->
			<canvas id="compressCanvas" style="position: fixed; z-index: -1; opacity: 0; top: -100%; left: -100%"></canvas>
		</div>
		<script src="../js/js/rem_fix.js"></script>
		<script src="../js/js/common.js"></script>
		<script type="text/javascript">
			var token = getCookie("userToken");
			var userId = getCookie("userId");
			var loginUrl = "../userBundle/login.mobile.html" + "?" + "../userBundle/tradingCenter.mobile.html";
			if (!token || !userId) {
				window.location.href = loginUrl;
			}
			require(["../js/js/base_config", "../js/js/better_scroll"], function(baseContent, BScroll) {
				var tradingCenterApp = new Vue({
					el: '#tradingCenter',
					data: {
						saleNumber: 0,
						buyNumber:0,
						showSaleJzz: false,
						isDoingFetchData: false,
						goldSeedAccountData: '',
						jzzListData: [],
						isLoading: false,
						isDoingUpload: false,
						userData: '',
						userDataOk: false,
						showBuyJzzInfo: false,
						currentBuyJzzInfo: '',
						payImgTempList: [], // 凭证  图片临时路径列表
						payImgUrlList: [], //凭证 存放七牛返回地址列表
						qiniuData: {
							key: "",
							token: ""
						},
						upload_qiniu_addr: '',
						currentBuyJzzData: '',
						itemPageNum:1,
						currentType:'2',
						showBuyJzz:false

					},
					filters:{
						formatData: function(key) {
							return formatDate(key)
						},
						status: function(key) {
							// 0 创建 1锁定 2上传  3 成交 9取消 
							key = parseInt(key);
							var map = {
								0: '创建中',
								1: '等待支付(锁定)',
								2:'已付款',
								3: '成交',
								9: '已取消'
							}
							return map[key];
						}
					},
					created: function() {
						$('#tradingCenter').show()
						this.fetchData();
						this.fetchJzzData();
						this.getUserInfo();
						this.loadItems();
						this.qiniuFetch()
					},
					methods: {
						showSaleData:function(){
							this.currentType='2';
							this.fetchData()
						},
						showBuyData:function(){
							this.currentType='1';
							this.fetchData()
						},
						getSellTotalPrice:function(price,number){
							return (price*number).toFixed(6)
						},
						fetchData: function() {
							if (this.isLoading) {
								return
							}
							var url = "/jzz/business";
							this.isLoading = true;
							var data = {
								client: "1",
								page: this.itemPageNum,
								size: 30,
								token: token,
								type: this.currentType,
								userId: userId
							}
							pushData(url, data, function(res) {
								this.isLoading = false
								if (res.state) {
									
									if (this.currentType == '1') {										
										this.jzzListData = res.data.business.buys
										this.totalItemPageCount=res.data.business.page
									} else {
										this.jzzListData = res.data.business.sales
										this.totalItemPageCount=res.data.business.page
									}

								} else {
									alert(res.message)
								}
							}.bind(this))
						},
						showBuyInfo: function(item) {
							this.showBuyJzzInfo = true;
							this.currentBuyJzzInfo = JSON.parse(item.payInfoJson)[0];
							this.currentBuyJzzData = item
						},
						toSellJzz:function(item){
							if(this.isDoingUpload){
								return
							}
							if(!this.userData){
								alert("网络延迟，重新点击出售")
								return
							}
							this.isDoingUpload=true;
							var url="/jzz/toSale"
							var bankInfo = JSON.parse(this.userData.bank)
							var data = {
								client: "1",
								id: item.id,
								payInfo: [{
									account: bankInfo.account,
									accountName: bankInfo.accountName,
									accountAddress:bankInfo.accountAddress,
									accountType: bankInfo.accountType,
									payType :''
								}],
								token: token,
								userId: userId
							}
							pushData(url, data, function(res) {
								this.isDoingUpload=false;
								if (res.state) {
									alert('订单已生成，等待对方打款')
									this.fetchData()
								} else {
									alert(res.message)
								}
							}.bind(this))
						},
						saleJzz: function() {
							if (!this.userDataOk) {
								alert("网络延迟，请再试一次")
								return
							}
							if (!this.goldSeedAccountData) {
								return
							}
							if (!this.userData.bank) {
								window.location.href = "./bankIdentification.mobile.html"
								return
							}
							this.showSaleJzz = true
						},
						confirmSaleJzz: function() {
							if (this.saleNumber > this.goldSeedAccountData.jzzNumber) {
								alert("超过你拥有的金种子")
								return
							}
							if (this.saleNumber <= 0) {
								alert("不能出售小于0个")
								return
							}
							var msg = "您将出售"+this.saleNumber+'lzb，手续费:'+this.saleNumber*0.005+'lzb';
							if (confirm(msg) == true) {
								this.isDoingUpload=true;
								
								var url = "/jzz/sale";
								var bankInfo = JSON.parse(this.userData.bank)
								
								var data = {
									client: "1",
									jzzNumber: parseFloat(this.saleNumber),
									payInfo: [{
										account: bankInfo.account,
										accountName: bankInfo.accountName,
										accountAddress:bankInfo.accountAddress,
										accountType: bankInfo.accountType,
										payType :''
									}],
									token: token,
									userId: userId
								}
								pushData(url, data, function(res) {
									this.isDoingUpload=false;
									if (res.state) {
										this.showSaleJzz = false;
										this.currentType='2';
										this.fetchData()
									} else {
										alert(res.message)
									}
								}.bind(this))
							}else{
								return
							}
							if(this.isDoingUpload){
								return
							}
							

						},
						showBuyJzzDemand:function(){
							this.showBuyJzz=true
						},
						confirmCreatedBuyJzz:function(){
							if(this.isDoingUpload){
								return
							}
							this.isDoingUpload=true;
							var url = "/jzz/buy"
							var data ={
								client: "1",
								jzzNumber: this.buyNumber,
								token: token,
								userId: userId
							}
							pushData(url, data, function(res) {
								this.isDoingUpload=false;
								if (res.state) {
									
									alert("求购成功");
									this.currentType='1';
									this.showBuyJzz=false;
									this.fetchData()
								} else {
									alert(res.data.result)
								}
							}.bind(this))
						},
						toBuyJzz: function() {
							var url = "/jzz/toBuy"
							var data = {
								client: "1",
								id: 0,
								payVoucher: '',
								token: token,
								userId: userId
							}
						},
						getUserInfo: function() {
							var url = "/user/getUserById";
							var data = {
								client: 1,
								token: token,
								userId: parseInt(userId)
							}
							pushData(url, data, function(res) {
								console.log(res)
								if (res.state) {
									this.userData = res.data.user;
									this.userDataOk = true
								} else if (res.errorCode == 008) {
									window.location.href = loginUrl;
								} else {
									alert(res.message)
								}
							}.bind(this))
						},
						fetchJzzData: function() {
							if (this.isDoingFetchData) {
								return
							}
							this.isDoingFetchData = true;
							var url = "/jzz/flow/user/getUserJzzInfo";
							var data = {
								client: 1,
								token: token,
								id: parseInt(userId),
								userId: parseInt(userId)
							}
							pushData(url, data, function(res) {
								this.isDoingFetchData=false
								if (res.state) {
									this.goldSeedAccountData = res.data.userInfo;
									this.saleNumber = this.goldSeedAccountData.jzzNumber
								} else {
									alert(res.message)
								}
							}.bind(this))
						},
						qiniuFetch: function() {
							var qiNiuData = {
								client: 1,
								token: token,
								userId: parseInt(userId)
							}
							pushData("/qiniu/get_token ", qiNiuData, function(res) {
								if (res.state) {
									this.qiniuData.token = res.data.result;
									console.log(res)
								} else if (res.errorCode == 008) {
									window.location.href = loginUrl;
								} else {
									alert(res.message)
								}
							}.bind(this));
							pushData("/qiniu/get_image_rul", qiNiuData, function(res) {
								if (res.state) {
									this.upload_qiniu_addr = res.data.url;
									console.log(res)
								} else if (res.errorCode == 008) {
									window.location.href = loginUrl;
								} else {
									alert(res.message)
								}
							}.bind(this));
						},
						_initUploadItemContentScroll: function() {
							var itemScroll = document.getElementById('itemScrollContent');
							console.log(itemScroll)
							if (!this.itemLoadBScroll) {
								this.itemLoadBScroll = new BScroll(itemScroll, {
									click: true,
									scrollY: true,
									scrollX: true,
									startX: 0,
									tap: true,
									pullUpLoad: {
										threshold: -40 // 当下拉到超过顶部 距离 时，触发 pullingDown 事件
									},
									pullDownRefresh: {
										threshold: 50, // 当下拉到超过顶部 50px 时，触发 pullingDown 事件
										stop: 20 // 刷新数据的过程中，回弹停留在距离顶部还有 20px 的位置
									}
								});

							} else { //如果存在但就刷新并且滚回最上面
								this.itemLoadBScroll.refresh();
								this.itemLoadBScroll.scrollTo(0, 0);
							}
						},
						loadItems: function() {
							this._initUploadItemContentScroll()
							/*下拉加载*/
							this.itemLoadBScroll.on('pullingUp', function() {
								this.itemLoadBScroll.finishPullUp();
								this.itemLoadBScroll.refresh();
								if (this.isLoading) {
									return;
								}
								if ((this.itemPageNum > this.totalItemPageCount) || this.totalItemPageCount == 1) {
									
									return
								}
								this.itemPageNum = parseInt(this.itemPageNum) + 1;
								this.fetchData();

							}.bind(this));
						},
						//选择图片
						onChooseImage: function(event, type) {
							var that = this;
							//判断图片数量是否已上限

							var currentImgTempArray = [];
							if (currentImgTempArray.length >= 5) {
								alert("最多上传5张图片");
								return false;
							}

							//使用FileReader对文件对象进行操作
							var reader = new FileReader();
							reader.readAsDataURL(event.target.files[0]); //将读取到的文件编码成Data URL
							console.log(event.target.files[0])

							reader.onload = function() { //读取完成时
								var replaceSrc = reader.result; //文件输出的内容
								//console.log(reader)
								//压缩图片处理
								var image = new Image();
								image.src = replaceSrc;
								image.onload = function() {
									//获取图片初始宽高
									var width = image.width;
									var height = image.height;
									//判断图片宽度，再按比例设置宽度和高度的值
									if (width > 1024) {
										width = 1024;
										height = Math.ceil(1024 * (image.height / image.width));
									}

									//将图片重新画入canvas中
									var canvas = document.getElementById("compressCanvas");
									var context = canvas.getContext("2d");
									canvas.width = width;
									canvas.height = height;
									context.beginPath();
									context.fillStyle = "#ffffff";
									context.fillRect(0, 0, width, height);
									context.fill();
									context.closePath();
									context.drawImage(image, 0, 0, width, height);
									replaceSrc = canvas.toDataURL("image/jpeg"); //canvas转DataURL(base64格式)

									//将压缩后的路径 追加到临时路径数组中
									var totalList = [];
									if (currentImgTempArray.length > 0) {
										totalList = currentImgTempArray.concat(replaceSrc);
									} else {
										totalList[0] = replaceSrc;
									}
									that.payImgTempList = totalList

									that.onUploadImg(totalList, type)
									//console.log(that.imgTempList)
								};
							};

						},
						onUploadImg: function(totalList, type) {
							var that = this;
							console.log(totalList)
							if (totalList.length > 0) {

								that.isUploading = true; //正在上传 显示遮罩层 防止连续点击

								var countNum = 0; //计算数量用的 判断上传到第几张图片了

								//map循环遍历上传图片
								totalList.map(function(imgItem, imgIndex) {
									var files = that.dataURLtoFile(imgItem, 'pj' + Date.now() + '.jpg'); //DataURL转File
									that.qiniuData.key = files.name;
									var formData = new FormData();
									formData.append('token', that.qiniuData.token)
									formData.append('key', that.qiniuData.key) //key为名称
									formData.append('file', files)
									// formData.token=that.qiniuData.token;
									//
									// formData.append("k1", "v1")							
									// formData.get("k1"); // "v1"
									console.log(formData)
									$.ajax({
										type: 'POST',
										url: 'http://upload.qiniup.com',
										contentType: false,
										data: formData,
										processData: false,
										async: false, //设置格式为同步非异步 不然可能会报错无法存储到临时变量/对象
										dataType: 'json',
										success: function(r) {
											console.log(r);
											//that.firstImgUrlList.push(that.upload_qiniu_addr + "/" + r.key);
											that.payImgUrlList.push(that.upload_qiniu_addr + "/" + r.key);
										},
										error: function(r) {
											console.log(r);
										}
									})
								});
							}
						},
						//删除某张图片
						deleteImg: function(idx, imageList) {
							var that = this;
							imageList.splice(idx, 1);
							this.payImgUrlList = []
						},

						/**
						 * 将base64转换为文件
						 * @dataUrl base64路径地址
						 * @fileName 自定义文件名字
						 * */
						dataURLtoFile: function(dataUrl, fileName) {
							var arr = dataUrl.split(','),
								mime = arr[0].match(/:(.*?);/)[1],
								bstr = atob(arr[1]),
								n = bstr.length,
								u8arr = new Uint8Array(n);
							while (n--) {
								u8arr[n] = bstr.charCodeAt(n);
							}
							return new File([u8arr], fileName, {
								type: mime
							});
						},
						confirmBuyJzz: function() {
							if (this.isDoingUpload) {
								return
							}
							
							this.isDoingUpload = true;
							var url = "/jzz/toBuy"
							// if (!this.payImgUrlList[0]) {
							// 	alert("请先转账并截图上传凭证后购买")
							// 	return
							// }
							var data = {
								client: "1",
								id: this.currentBuyJzzData.id,						
								token: token,
								userId: parseInt(userId)
							}							
							pushData(url, data, function(res) {
								this.isDoingUpload = false;
								if (res.state) {
									alert("锁定成功，请在30分钟内完成付款并上传截图")
									window.location.href = "./myJzzBusiness.mobile.html"
								} else {
									alert(res.data.result)
								}
							}.bind(this))
						},
					}
				})
			})
		</script>

	</body>
</html>
